package com.zzz.offer.addTwoNumbers;


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    public String toString() {
        ListNode cur = this;
        StringBuilder s = new StringBuilder();
        while (cur != null) {
            s.append(cur.val).append("  ");
            cur = cur.next;
        }
        return s.toString();
    }
}


public class Solution {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(7);

        System.out.println(addTwoNumbers(l1, l2));

    }


    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode curL1 = l1;
        ListNode curL2 = l2;

        int next = 0;

        ListNode result = null;
        ListNode curResult = null;
        while (curL1 != null || curL2 != null) {

            int cur;
            if(curL1 != null  && curL2 != null)
                cur = curL1.val + curL2.val + next;
            else if(curL1 != null)
                cur = curL1.val + next;
            else
                cur = curL2.val + next;

            next = cur / 10;
            cur = cur % 10;

            ListNode nextNode = new ListNode(cur);
            if (result != null) {
                curResult.next = nextNode;
                curResult = curResult.next;
            } else {
                result = nextNode;
                curResult = result;
            }

            if(curL1 != null) {
                curL1 = curL1.next;
            }
            if(curL2 != null) {
                curL2 = curL2.next;
            }
        }

        if (next > 0) {
            curResult.next = new ListNode(next);
        }
        return result;
    }
}
